<?php

class WidgetCode extends CCodeModel
{

	public $className;
	public $widgetPath;

	public function rules()
	{
		return array_merge(parent::rules(), array(
					array('className', 'required'),
					array('className', 'match', 'pattern' => '/^\w+$/'),
					array('widgetPath', 'match', 'pattern' => '/^[\w\.]+$/'),
				));
	}

	public function attributeLabels()
	{
		return array_merge(parent::attributeLabels(), array(
					'className' => 'Widget Class Name',
					'widgetPath' => 'Widget Path'
				));
	}

	public function prepare()
	{
		if (empty($this->widgetPath))
			$this->widgetPath = 'application.components.';
		//if (strpos($this->className,'.')===false) $this->className = 'application.components.'.$this->className;
		$widgetPath = Yii::getPathOfAlias($this->widgetPath) . DIRECTORY_SEPARATOR . $this->className;
		$widgetFile = $widgetPath . DIRECTORY_SEPARATOR . $this->className . '.php';
		$widgetTemplateFile = $this->templatepath . DIRECTORY_SEPARATOR . 'widget.php';

		$code = $this->render($widgetTemplateFile);

		$this->files[] = new CCodeFile($widgetFile, $code);

		$files = CFileHelper::findFiles($this->templatepath, array(
					'exclude' => array('.svn'),
				));

		foreach ($files as $file)
		{
			if ($file !== $widgetTemplateFile)
			{
				if (CFileHelper::getExtension($file) === 'php')
				{
					$content = $this->render($file);
				}
				else if (basename($file) === '.yii')
				{  // an empty directory
					$file = dirname($file);
					$content = null;
				}
				else
				{
					$content = file_get_contents($file);
				}
				$this->files[] = new CCodeFile(
								$widgetPath . str_replace('WidgetId', $this->className, substr($file, strlen($this->templatepath))),
								$content
				);
			}
		}
	}

}